package com.yzt.insys.control;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.yzt.insys.beans.User;
import com.yzt.insys.dto.RolePowerDto;
import com.yzt.insys.dto.UserDto;
import com.yzt.insys.service.PowerService;
import com.yzt.insys.service.RolePowerService;
import com.yzt.insys.service.UserService;
import com.yzt.insys.util.UserToken;
import com.yzt.insys.util.UserUtil;

/**
 * @作者 zsf
 * @时间 2013-6-20
 */
@Scope("prototype")
@Controller
public class MainControl extends BaseControl {

	@SuppressWarnings("unused")
	private Logger logger=Logger.getLogger(getClass());
	@Resource
	@Qualifier("userService")
	private UserService uService;

	@Resource
	@Qualifier("rolePowerService")
	private RolePowerService rpService;

	@Resource
	private PowerService pService;
	
	/**
	 * 登陆
	 */
	@RequestMapping(value="/login",method={RequestMethod.POST,RequestMethod.GET})
	public String login(RedirectAttributes redirectAttributes,User user) throws Exception {
			forward="index";	
			Subject subject=SecurityUtils.getSubject();
			if(!subject.isAuthenticated()){
				String suffiix=getServletContext().getInitParameter("suffix");
				forward=INDEX+suffiix;
				if (user == null || user.getUserName() == null|| user.getUserPwd() == null) {
					redirectAttributes.addFlashAttribute("msg","用户名或密码错误！");
					return forward;
				}
				UserToken userToken=new UserToken(user,true);
				try {
					subject.login(userToken);
					user=getUserFromSession();
					List<RolePowerDto> rpList=rpService.queryAllSupPowersByRoleIds(UserUtil.getRoleIds(user.getRoles()));
					sesAddAttr("supPowers",rpList);
					rpList=rpService.queryAllPowersByRoleIds(UserUtil.getRoleIds(user.getRoles()));
					sesAddAttr("powerKeys",getAllPowerMasterName(rpList));
					forward="index";
				} catch (UnknownAccountException e) {
					e.printStackTrace();
					redirectAttributes.addFlashAttribute("msg", "用户名或密码错误！");
				} catch (IncorrectCredentialsException e) {
					e.printStackTrace();
					redirectAttributes.addFlashAttribute("msg", "用户名或密码错误！");
				} catch (LockedAccountException e) {
					e.printStackTrace();
					redirectAttributes.addFlashAttribute("msg", "用户已经被锁定不能登录，请与管理员联系！");
				} catch (ExcessiveAttemptsException e) {
					e.printStackTrace();
					redirectAttributes.addFlashAttribute("msg", "错误次数过多！");
				} catch (AuthenticationException e) {
					e.printStackTrace();
					redirectAttributes.addFlashAttribute("msg", "未知的登录错误！");
				}
			}
		return forward;
	}

	private List<String> getAllPowerMasterName(List<RolePowerDto> rpList){
		List<String> resultList=new ArrayList<String>(); 
		for(RolePowerDto rpDto :rpList){
			resultList.add(rpDto.getMasterName());
		}
		return resultList;
	}
	@ResponseBody
	@RequestMapping(value={"/relogin","/app/login"},method={RequestMethod.POST,RequestMethod.GET})
	public String relogin(User user){
		paramMap=getParamMap();
		if (user==null||user.getUserName()==null||user.getUserPwd()== null) {
			msg="false";
		} else {
			UserToken userToken=new UserToken(user,true);
			Subject subject=SecurityUtils.getSubject();
			try {
				subject.login(userToken);
				user=getUserFromSession();
				List<RolePowerDto> rpList=rpService.queryAllSupPowersByRoleIds(UserUtil.getRoleIds(user.getRoles()));
				sesAddAttr("supPowers",rpList);
				msg="true";
				UserUtil.saveUserToCookie(response,user);
			} catch (UnknownAccountException e) {
				e.printStackTrace();
				msg="false";
			} catch (IncorrectCredentialsException e) {
				e.printStackTrace();
				msg="false";
			} catch (LockedAccountException e) {
				msg="false";
			} catch (ExcessiveAttemptsException e) {
				e.printStackTrace();
				msg="false";
			} catch (AuthenticationException e) {
				e.printStackTrace();
				msg="false";
			}
		}
		return msg;
	}
	
	@ResponseBody
	@RequestMapping(value="/tree",method={RequestMethod.POST,RequestMethod.GET})
	public synchronized Object  generateTree(@RequestParam("fatherId") Long fatherId,Long id){
			UserDto user=getUserFromSession();
			paramMap.clear();
			paramMap.put("fatherId",id==null?fatherId:id);
			paramMap.put("roleId",UserUtil.getRoleIds(user.getRoles()));
			paramMap.put("roleIds",UserUtil.getRoleIds(user.getRoles()));
			return JSON.toJSON(pService.queryPowersByFatherId(paramMap));
	}
	/**
	 * 退出
	 */
	@ResponseBody
	@RequestMapping(value = "/exit")
	public String exit() {
		Subject subject=SecurityUtils.getSubject();
		subject.logout();
		cleanCache();
		return "success";
	}
	
	@RequestMapping(value = "/*/all/{masterName}")
	public synchronized String toAll(@PathVariable("masterName")String masterName) {
		reqAddAttr("powers",pService.querySubPowerByMasterName(masterName));
		return "commons/all";
	}
	
	/**
	 * 跳转到添加页面
	 */
	@RequestMapping("/*/toAdd")
	public synchronized String toAdd(){
		reqAddAttr("paramMap",getParamMap());
		return forward_toAdd();
	}
	
	@RequestMapping("/goLogin")
	public String goLogin(){
		cleanCache();
		return "login";
	}
	
	
	/**
	 * 清除缓存
	 */
	private void cleanCache(){
		response.setHeader("Pragma","No-cache"); 
		response.setHeader("Cache-Control","no-cache"); 
		response.setDateHeader("Expires", 0); 
		response.setHeader("Cache-Control","no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
	}
}
